import DexieCtx from '@/utils/dexiectx';
import Config from '@/utils/config';
import { Api, TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'

class TimefarmTgweb {
  constructor() {
  }

  async allRun() {
    this.dexie = await DexieCtx.db()
    const allAccounts = await this.dexie.accounts.where("session").notEqual("").toArray()
    const project = await this.dexie.projects.get({
      name: "timefarm"
    })
    // 用户没设置邀请url，则使用我们自己的邀请url
    let inviteList = project.inviteList ?? []
    if (inviteList.length == 0) {
      inviteList = ["https://t.me/TimeFarmCryptoBot/timefarm?start=1fsbUoPPmYMIHylaN"];
    }
    let sepIndex = 0;
    const groupStep = 10
    while (true) {
      if (sepIndex >= allAccounts.length) {
        break;
      }
      const start = sepIndex
      const end = Math.min(sepIndex + groupStep, allAccounts.length)
      const accountsGroup = allAccounts.slice(start, end)
      try {
        const allClients = accountsGroup.map(item => {
          const strSession = new StringSession(item.session)
          const client = new TelegramClient(strSession, Config.API_ID, Config.API_HASH, {
            connectionRetries: 3,
            useWSS: true,
            timeout: 20,
          })
          client.phone = item.phone
          return client
        })
        if (inviteList.length > 0) {
          for (let index = 0; index < allClients.length; index++) {
            const client = allClients[index];
            const realIndex = index + start
            const inviteUrl = inviteList[realIndex % inviteList.length]
            client.inviteUrl = inviteUrl
          }
        }
        const promiseGroup = allClients.map(client => {
          return this.run(client)
        })
        await Promise.allSettled(promiseGroup)
        console.log(Date() + "timefarm tgweb finished " + start + "~" + end)
      } catch (error) {
        console.error(error)
      } finally {
        sepIndex = end
      }
    }
  }

  async run(client) {
    try {
      await client.connect();
      const isAuth = await client.checkAuthorization()
      if (isAuth != true) {
        throw new Error("unauth");
      }
      const user = await client.getInputEntity('TimeFarmCryptoBot');
      // start-bot
      const inviteUrl = client.inviteUrl
      const startParam = inviteUrl == null ? null : inviteUrl.split("start=")[1]
      const botResult = await client.invoke(
        new Api.messages.StartBot({
          bot: "TimeFarmCryptoBot",
          peer: user,
          randomId: Date.now(),
          startParam: startParam,
        })
      );
      console.log(client.phone, "startBot", botResult)

      const result = await client.invoke(
        new Api.messages.RequestWebView({
          peer: user,
          bot: "TimeFarmCryptoBot",
          fromBotMenu: false,
          url: (inviteUrl || "https://t.me/TimeFarmCryptoBot/timefarm?start=1fsbUoPPmYMIHylaN"),
          platform: "android"
        })
      );
      const url = result.url;
      await this.updateTimefarmTable(client.phone, url)
    } catch (error) {
      console.error(client.phone, error)
    } finally {
      try {
        await client.disconnect()
        await client.destroy()
      } catch (error) {
      }
    }

  }

  async updateTimefarmTable(phone, tgweb) {
    const oldValue = await this.dexie.timefarm.get({
      phone: phone
    })
    const dateStr = (new Date()).toLocaleString()
    if (oldValue == null) {
      await this.dexie.timefarm.add({
        phone,
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    } else {
      await this.dexie.timefarm.where("phone").equals(phone).modify({
        tgweb: tgweb,
        tokenupdate: dateStr,
      })
    }
  }
}

export default TimefarmTgweb